package com.february.todo;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.february.todo.DataBase.DataBaseOperate;
import com.february.todo.tools.NavigateBar;
import com.february.todo.tools.TimeComparator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class StatisticsActivity extends AppCompatActivity {

    private TextView tv_startDate;
    private TextView tv_endDate;
    private ImageButton imgbtn_startDate;
    private ImageButton imgbtn_endDate;
    private Button btn_confirm;
    private LineChartView lineChart;
    private DataBaseOperate dataBaseOperate;
    private String startDate;
    private String endDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistics);

        NavigateBar navigateBar = findViewById(R.id.navigateBar);
        navigateBar.setContext(this);

        tv_startDate = findViewById(R.id.startDate);
        tv_endDate = findViewById(R.id.endDate);
        imgbtn_startDate = findViewById(R.id.imgbtn_startDate);
        imgbtn_endDate = findViewById(R.id.imgbtn_endDate);
        btn_confirm = findViewById(R.id.btn_confirm);
        lineChart = findViewById(R.id.lineChart);

        dataBaseOperate = new DataBaseOperate(this);
        initTextView();
        initLineChartView();
        initEvent();
    }

    void initTextView() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M", Locale.CHINA); //设置时间格式
        Date curTime = new Date(System.currentTimeMillis()); //获取当前时间
        startDate = formatter.format(curTime) + "-1";
        tv_startDate.setText(startDate);
        endDate = formatter.format(curTime) + "-28";
        tv_endDate.setText(endDate);
    }

    void initEvent() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-d", Locale.CHINA); //设置时间格式
        imgbtn_startDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerBuilder(StatisticsActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        startDate = formatter.format(date);
                        tv_startDate.setText(startDate);
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})//分别对应年月日时分秒，默认全部显示
                        .isDialog(true)
                        .build();

                Dialog mDialog = pvTime.getDialog();
                if (mDialog != null) {

                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            Gravity.BOTTOM);

                    params.leftMargin = 0;
                    params.rightMargin = 0;
                    pvTime.getDialogContainerLayout().setLayoutParams(params);

                    Window dialogWindow = mDialog.getWindow();
                    if (dialogWindow != null) {
                        dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                        dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                    }
                }
                pvTime.show();
            }
        });

        imgbtn_endDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerBuilder(StatisticsActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        endDate = formatter.format(date);
                        tv_endDate.setText(endDate);
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})//分别对应年月日时分秒，默认全部显示
                        .isDialog(true)
                        .build();

                Dialog mDialog = pvTime.getDialog();
                if (mDialog != null) {

                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                            Gravity.BOTTOM);

                    params.leftMargin = 0;
                    params.rightMargin = 0;
                    pvTime.getDialogContainerLayout().setLayoutParams(params);

                    Window dialogWindow = mDialog.getWindow();
                    if (dialogWindow != null) {
                        dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                        dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                    }
                }
                pvTime.show();
            }
        });

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initLineChartView();
            }
        });
    }

    void initLineChartView() {
        List<PointValue> mPointValues = new ArrayList<PointValue>();
        List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-M-d", Locale.CHINA);
        try {
            int i = 0;
            Date tempDate = formatter.parse(startDate);
            while (new TimeComparator(tempDate, endDate).isEarlier) {
                assert tempDate != null;
                String t = formatter.format(tempDate);
                mAxisXValues.add(new AxisValue(i).setLabel(t));
                mPointValues.add(new PointValue(i, dataBaseOperate.countTodo(t)));
                tempDate.setTime(tempDate.getTime() + 60 * 60 * 24 * 1000);
                i++;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(false);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
//      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        ArrayList<Line> lines = new ArrayList<Line>();
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.GRAY);  //设置字体颜色
        //axisX.setName("date");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(7); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setName("");//y轴标注
        axisY.setTextSize(10);//设置字体大小
        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //data.setAxisYRight(axisY);  //y轴设置在右边


        //设置行为属性，支持缩放、滑动以及平移
        lineChart.setInteractive(true);
        lineChart.setZoomType(ZoomType.HORIZONTAL);
        lineChart.setMaxZoom((float) 2);//最大方法比例
        lineChart.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        lineChart.setLineChartData(data);
        lineChart.setVisibility(View.VISIBLE);
        /*注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
        Viewport v = new Viewport(lineChart.getMaximumViewport());
        v.left = 0;
        v.right = 7;
        lineChart.setCurrentViewport(v);
    }
}